package com.hc.comm.utils;

import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.Map;

/**
 * xss工具类
 *
 * @author
 */
public class XssUtil {

    private static Logger logger = Logger.getLogger(XssUtil.class);

    /**
     * 过滤xss攻击
     *
     * @param request
     */
    @SuppressWarnings("unchecked")
    public static boolean filterXss(HttpServletRequest request) {
        boolean result = true;
        // 过滤掉一些可能引起攻击的代码
        Map<String, Object> paramMap = request.getParameterMap();
        XssHTMLUtil xssHTMLUtil = new XssHTMLUtil();
        for (Iterator<String> iter = paramMap.keySet().iterator(); iter
                .hasNext(); ) {
            String key = iter.next();
            Object obj = paramMap.get(key);
            if (obj != null && (obj instanceof String[])) {
                String[] paraValues = (String[]) obj;
                for (int i = 0; i < paraValues.length; i++) {
                    String originalValue = paraValues[i];
                    //TODO 注释掉，过滤有问题
                    //paraValues[i] = xssHTMLUtil.filter(paraValues[i]);
                    if (originalValue != null
                            && !originalValue.equals(paraValues[i])) {
                        logger.info("xss:[key=" + key + ",originalValue="
                                + originalValue + ",value=" + paraValues[i]);
                        result = false;
                    }
                }
            }
        }
        return result;
    }
}
